//
//  YSAVObject.m
//  WHISPER
//
//  Created by lanou3g on 15/12/29.
//  Copyright © 2015年 王艳苹. All rights reserved.
//

#import "YSAVObject.h"
#import "AVObject.h"
#import "AVQuery.h"
#import "CollectModel.h"
static YSAVObject *object = nil;

@interface YSAVObject ()

@property(nonatomic,strong)NSMutableArray *arr;

@end

@implementation YSAVObject

+(instancetype)shareAVObject{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        object = [[YSAVObject alloc]init];
    });
    return object;
}

//增加一条数据
-(void)inseartToAvObjectWithTitle:(NSString *)title Url:(NSString *)url userName:(NSString *)userName {
    AVObject *post = [AVObject objectWithClassName:@"Post"];
    [post setObject:title forKey:@"title"];
    [post setObject:url forKey:@"url"];
    [post setObject:userName forKey:@"userName"];
    [post saveInBackground];
}

//删除
-(void)deleteForAvObjectWithTitle:(NSString *)title Url:(NSString *)url userName:(NSString *)userName {
    AVQuery *query = [AVQuery queryWithClassName:@"Post"];
    [query whereKey:@"url" equalTo:url];
    [query whereKey:@"userName" equalTo:userName];
    [query whereKey:@"title" equalTo:title];
    AVObject *post = [query getFirstObject];;
    [post deleteInBackground];
}

- (void)isCollectionWithUrl:(NSString*)url userName:(NSString *)userName block:(void(^)(BOOL isCollection))block{
    AVQuery *query = [AVQuery queryWithClassName:@"Post"];
    [query whereKey:@"url" equalTo:url];
    [query whereKey:@"userName" equalTo:userName];
    [query getFirstObject];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (objects.count == 0 || error) {
            block(NO);
        }
        block(YES);
    }];
}

-(NSMutableArray *)queryArray:(NSString *)userName {
    if (self.arr.count > 0) {
        [_arr removeAllObjects];
    }
    AVQuery *query = [AVQuery queryWithClassName:@"Post"];
    [query whereKey:@"userName" equalTo:userName];
    NSArray *result = [query findObjects];
    for (NSDictionary *dic in result) {
       CollectModel *model = [[CollectModel alloc]init];
       [model setValuesForKeysWithDictionary:dic[@"localData"]];
       [_arr addObject:model];
    }
    return _arr ;
}

-(NSMutableArray *)arr{
    if (_arr == nil) {
        _arr = [NSMutableArray array];
    }
    return _arr;
}


@end
